package com.j48.entrancegurad.controller;

import com.j48.entrancegurad.model.A_C;
import com.j48.entrancegurad.model.Admin;
import com.j48.entrancegurad.model.Character;
import com.j48.entrancegurad.service.IA_CService;
import com.j48.entrancegurad.service.IAdminService;
import com.j48.entrancegurad.service.ICharacterService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class AdminController {
    @Autowired
    private IAdminService adminservice;
    @Autowired
    private ICharacterService characterService;
    @Autowired
    private IA_CService acservice;

    /**
     * 管理员列表查询
     * @param request
     * @return 页面
     */
    @RequestMapping("adminList")
    @ResponseBody
    public ModelAndView adminList(HttpServletRequest request){
        ModelAndView modelAndView=null;
        List<Admin> lists = new ArrayList<Admin>();
        lists = adminservice.selectAll();
        List<Integer> aidList=new ArrayList<>();
        List<Integer> cidList=new ArrayList<>();
        List<Character> characterList=new ArrayList<>();
        if(lists!=null) {
            for (Admin a : lists) {
                int i = a.getAdmin_id();
                aidList.add(i);
            }
            for (int i:aidList){
                Admin admin=new Admin();
                admin.setAdmin_id(i);
                A_C a_c=acservice.select(admin);
                cidList.add(a_c.getA_c_character_id());
            }
            for (int i:cidList) {
                Character character=new Character();
                character.setCharacter_id(i);
                character=characterService.selectById(character);
                characterList.add(character);
            }
        }
        modelAndView=new ModelAndView("jsp/admin_index");
        request.getSession().setAttribute("adminCharacter",characterList);
        request.getSession().setAttribute("admin1",lists);
        return modelAndView;
    }

    /**
     * 管理员查询
     * @param admin 被查询的管理员
     * @param request
     * @return 页面
     */
    @RequestMapping("/selectAdmin")
    @ResponseBody
    public ModelAndView selectAdmin(Admin admin,HttpServletRequest request){
        ModelAndView model=null;
        String adminName=admin.getAdmin_username();
        Admin ad=new Admin();
        ad=adminservice.selectOne(admin);
        List<Admin> lists = new ArrayList<Admin>();
        List<Integer> aidList=new ArrayList<>();
        List<Integer> cidList=new ArrayList<>();
        List<Character> characterList=new ArrayList<>();
        if (adminName.equals("") || adminName == null) {// admin_username为空，查询全部管理员信息
            return adminList(request);
        } else {// 通过管理员编号查询
            if (ad==null){
                System.out.println("未找到该管理员");
            }else {
                lists.add(ad);
                if(lists!=null) {
                    for (Admin a : lists) {
                        int i = a.getAdmin_id();
                        aidList.add(i);
                    }
                    for (int i:aidList){
                        Admin admin1=new Admin();
                        admin1.setAdmin_id(i);
                        A_C a_c=acservice.select(admin1);
                        cidList.add(a_c.getA_c_character_id());
                    }
                    for (int i:cidList) {
                        Character character=new Character();
                        character=characterService.selectById(character);
                        characterList.add(character);
                    }
                }
            }
        }

        model=new ModelAndView("jsp/admin_index");
        request.getSession().setAttribute("admin1",lists);
        request.getSession().setAttribute("adminCharacter",characterList);
        request.getSession().setAttribute("counts",lists.size());
        return model;
    }

    /**
     * 添加管理员
     * @param admin 被添加的管理员
     * @param request
     * @return 页面
     */
    @RequestMapping("/adminAddController")
    @ResponseBody
    public ModelAndView adminAddController(Admin admin ,HttpServletRequest request){
        System.out.println("进入");
        ModelAndView model=null;
        String charName=request.getParameter("charName");
        System.out.println(charName);
        Character character =new Character(charName);
        ArrayList<Character> ch=characterService.selectcharacter(character);
        int characterId=ch.get(0).getCharacter_id();//获取添加角色的ID
        String password= DigestUtils.md5Hex(admin.getAdmin_password());//md5加密
        admin.setAdmin_password(password);//通过set方法，将密码设置成md5格式
        Date date = new Date();
        Timestamp admin_time=new Timestamp(date.getTime());
        Admin ad=new Admin(admin.getAdmin_username(),admin.getAdmin_password(),admin.getAdmin_name(),admin.getAdmin_phone(),admin_time);
        if (adminservice.selectOne(ad)!=null){
            model=new ModelAndView("jsp/failure");
        }else {
            if (adminservice.addAdmin(ad)){
                int adminId=adminservice.selectOne(ad).getAdmin_id();//获取管理员的ID
                A_C ac =new A_C(adminId,characterId);
                if (acservice.add(ac)){
                    model=new ModelAndView("jsp/success");
                }
            }else {
                model=new ModelAndView("jsp/failure");
            }
        }
        return model;
    }

    /**
     * 查询被修改管理员信息
     * @param request
     * @return 查询结果
     */
    @RequestMapping("/deleteOrUpdateAdminController")
    @ResponseBody
    public String deleteOrUpdateAdminController(HttpServletRequest request){
        int admin_id=Integer.parseInt(request.getParameter("admin_id"));
        Admin admin=new Admin();
        admin.setAdmin_id(admin_id);
        Admin admin1=adminservice.selectById(admin);
        int i=acservice.select(admin1).getA_c_character_id();
        Character character=new Character();
        character.setCharacter_id(i);
        character=characterService.selectById(character);
        request.getSession().setAttribute("adminselected",admin1);
        request.getSession().setAttribute("adminCharaceterSelected",character);
        if(admin1!=null){
            return "true";
        }
        return "false";
    }

    /**
     * 管理员离职
     * @param request
     * @return 成功与否
     */
    @RequestMapping("deleteAdmin")
    @ResponseBody
    public String deleteAdmin(HttpServletRequest request){
        request.getSession().removeAttribute("admin1");
        int admin_id=Integer.parseInt(request.getParameter("admin_id"));
        Admin admin=new Admin();
        admin.setAdmin_id(admin_id);
        if(adminservice.deleteAdmin(admin)){
            A_C a_c=new A_C();
            a_c.setA_c_admin_id(admin_id);
            if(acservice.deleteadmin(a_c)) {
                return "true";
            }
        }
        return "false";
    }

    /**
     * 跳转到管理员修改页面
     * @param request
     * @param response
     * @return 页面
     */
    @RequestMapping("toAdminUpdate")
    @ResponseBody
    public ModelAndView toAdminUpdate(HttpServletRequest request,HttpServletResponse response){
        ModelAndView modelAndView=new ModelAndView("/jsp/adminUpdate");
        return  modelAndView;
    }

    /**
     * 修改管理员信息
     * @param admin 被修改后的管理员信息
     * @param charName 被修改后的角色信息
     * @param request
     * @return 页面
     */
    @RequestMapping("/updateAdminController")
    @ResponseBody
    public ModelAndView updateAdminController(Admin admin,String charName,HttpServletRequest request){
        ModelAndView model=null;
        Character character=new Character();
        character.setCharacter_name(charName);
        Character character1=characterService.selectcharacter(character).get(0);
        String password= DigestUtils.md5Hex(admin.getAdmin_password());
        int i=character1.getCharacter_id();
        A_C a_c=acservice.select(admin);
        a_c.setA_c_character_id(i);

        admin.setAdmin_password(password);
        if (adminservice.updateAdmin(admin)&& acservice.update(a_c)){
            model=new ModelAndView("jsp/success1");
        }else {
            model=new ModelAndView("jsp/failure1");
        }
        return model;
    }

    @RequestMapping("/findadminname")
    @ResponseBody
    public void selectadminname(HttpServletResponse resp,HttpServletRequest req,Admin admin) throws IOException {
        String adminusername=req.getParameter("admin_username");
        PrintWriter w=resp.getWriter();
        ArrayList<Admin> admin1=new ArrayList<Admin>();
        admin.setAdmin_username(adminusername);
        admin1=adminservice.selectByUserName(admin);
        if(admin1.size()>0){
            w.write("true");
        }else{
            w.write("false");
        }
    }

    /**
     * 退出清除所有session
     * @param req
     * @param model
     * @return 页面
     * @throws IOException
     */
    @RequestMapping("/clearAllSession")
    @ResponseBody
    public ModelAndView clearAllSessions(HttpServletRequest req,ModelAndView model) throws IOException {
        Admin admin=new Admin();
        admin=(Admin)req.getSession().getAttribute("admin");
        adminservice.updataLogin1(admin);
        req.getSession().invalidate();
        model=new ModelAndView("jsp/loginofall");
        return model;
    }

}
